package com.snowwolf.snowmail.core;

import com.snowwolf.snowmail.core.attach.InputStreamMailAttach;
import com.snowwolf.snowmail.core.attach.MailAttach;
import com.snowwolf.snowmail.core.datasource.InputStreamDataSource;
import com.snowwolf.snowmail.core.sign.ISign;
import com.snowwolf.snowmail.core.templete.IMailTemplete;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

/**
 * Created by snowwolf-louis on 17/11/23.
 */
public class MailUtil {

    public static void sendEmail(MailConfig mailConfig,String receiveEmailAddr, IMailTemplete iMailTemplete) throws IOException, MessagingException, InvocationTargetException, IllegalAccessException {
        sendEmail(mailConfig,receiveEmailAddr, iMailTemplete,null,null);
    }

    public static void sendEmail(MailConfig mailConfig,String receiveEmailAddr, IMailTemplete iMailTemplete,ISign iSign) throws IOException, MessagingException, InvocationTargetException, IllegalAccessException {
        sendEmail(mailConfig,receiveEmailAddr, iMailTemplete,null,iSign);
    }

    public static void sendEmail(MailConfig mailConfig,String receiveEmailAddr, IMailTemplete iMailTemplete, List<MailAttach> mailAttaches) throws MessagingException, IOException, InvocationTargetException, IllegalAccessException {
        sendEmail(mailConfig,receiveEmailAddr, iMailTemplete, mailAttaches, null);
    }

    public static void sendEmail(MailConfig mailConfig,String receiveEmailAddr, IMailTemplete iMailTemplete, List<MailAttach> mailAttaches, ISign isign) throws MessagingException, IOException, InvocationTargetException, IllegalAccessException {
        MailBean mailBean = new MailBean();
        BeanUtils.copyProperties(mailBean,mailConfig);

        mailBean.setTo(receiveEmailAddr);
        mailBean.setSubject(iMailTemplete.getSubject());
        mailBean.setContent(iMailTemplete.getContent());

        if (mailAttaches != null && !mailAttaches.isEmpty()) {
            List<MailAttach> list = new ArrayList<MailAttach>();
            for (MailAttach mailAttach : mailAttaches) {
                list.add(mailAttach);
            }
            mailBean.setMailAttaches(list);
        }

        mailBean.setIsign(isign);


        sendMessage(mailBean);
    }

    private static void sendMessage(MailBean mailBean) throws MessagingException, IOException {
        // 配置发送邮件的环境属性
        final Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", mailBean.getHost());
        props.put("mail.smtp.port", mailBean.getPort());
        // 发件人的账号
        props.put("mail.user", mailBean.getFrom());
        // 访问SMTP服务时需要提供的密码
        props.put("mail.password", mailBean.getPassword());


        // 构建授权信息，用于进行SMTP进行身份验证
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // 用户名、密码
                String userName = props.getProperty("mail.user");
                String password = props.getProperty("mail.password");
                return new PasswordAuthentication(userName, password);
            }
        };
        // 使用环境属性和授权信息，创建邮件会话
        Session mailSession = Session.getInstance(props, authenticator);
        // 创建邮件消息
        MimeMessage message = new MimeMessage(mailSession);

        // 设置发件人
        String nick = toChinese(mailBean.getUsername());
        InternetAddress form = new InternetAddress(
                props.getProperty("mail.user"));

        message.setFrom(new InternetAddress(nick + "<" + form + ">"));


        // 设置收件人
        if (StringUtils.isNotBlank(mailBean.getTo())) {
            @SuppressWarnings("static-access")
            InternetAddress[] internetAddressTo = new InternetAddress().parse(mailBean.getTo());
            message.setRecipients(MimeMessage.RecipientType.TO, internetAddressTo);
        }


        // 设置邮件标题
        message.setSubject(mailBean.getSubject());

        // 设置邮件的内容体
        MimeMultipart msgMultipart = getContent(mailBean.getContent(), mailBean.getMailAttaches(), mailBean.getIsign());
        message.setContent(msgMultipart);

        // 发送邮件
        Transport.send(message);
    }

    private static MimeMultipart getContent(String emailContent, List<MailAttach> mailAttaches, ISign iSign) throws MessagingException, IOException {
        //整封邮件的MINE消息体
        MimeMultipart msgMultipart = new MimeMultipart("mixed");//混合的组合关系


        if (mailAttaches != null && !mailAttaches.isEmpty()) {
            for (MailAttach mailAttach : mailAttaches) {
                //附件
                MimeBodyPart attch = new MimeBodyPart();
                //把文件，添加到附件中

                //数据处理器
                DataHandler dh = null;
                dh = new DataHandler(new InputStreamDataSource(mailAttach.getInputStream(), mailAttach.getFileName()));
                //设置第一个附件的数据
                attch.setDataHandler(dh);
                //设置第一个附件的文件名
                attch.setFileName(mailAttach.getFileName());

                msgMultipart.addBodyPart(attch);
            }
        }


        //正文内容
        MimeBodyPart content = new MimeBodyPart();

        //正文（图片和文字部分
        MimeMultipart bodyMultipart = new MimeMultipart("related");
        //html代码部分
        MimeBodyPart htmlPart = new MimeBodyPart();
        //正文html代码
        htmlPart.setContent(emailContent, "text/html;charset=UTF-8");

        bodyMultipart.addBodyPart(htmlPart);


        // 签名
        if (iSign != null){
            //前置内容
            MimeBodyPart preposePart = new MimeBodyPart();
            preposePart.setContent(iSign.getPrepose(), "text/html;charset=UTF-8");
            bodyMultipart.addBodyPart(preposePart);

            //图片
            MimeBodyPart imgPart = new MimeBodyPart();
            DataSource imgds = new FileDataSource(iSign.getFilePath());
            DataHandler imgdh = new DataHandler(imgds);
            imgPart.setDataHandler(imgdh);
            imgPart.setFileName("sign.jpg");
            imgPart.setHeader("Content-ID", "<IMGsign>");
            bodyMultipart.addBodyPart(imgPart);

            MimeBodyPart imgBody = new MimeBodyPart();
            imgBody.setContent("<html><body><img src='cid:IMGsign' ></body><html><br>", "text/html;charset=UTF-8");
            bodyMultipart.addBodyPart(imgBody);

            //后置内容
            MimeBodyPart postposePart = new MimeBodyPart();
            postposePart.setContent(iSign.getPostpose(), "text/html;charset=UTF-8");
            bodyMultipart.addBodyPart(postposePart);
        }

        //设置内容为正文
        content.setContent(bodyMultipart);

        msgMultipart.addBodyPart(content);
        return msgMultipart;
    }

    private static String toChinese(String text) {
        try {
            return MimeUtility.encodeText(text);
        } catch (UnsupportedEncodingException e) {
            return "";
        }
    }


    public static void main(String args[]) throws IOException {
        String ReceiveEmail = "mei.xin@wowoohr.com";
        String CCEmail = "";
        String city = "上海";
        String name = "潘平";
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日   HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String str = formatter.format(curDate);
        String titleEmail = "2017年02月人力窝账单";
        String htmlbody = "亲爱的客户，您好！<br><br>"
                + "****年**月的账单已经系统生成,账单总金额为**元。您可以登陆人力窝的在线平台，通过“账单管理界面”看到您这个月的账单。<br><br>"
                + "若您对账单没有异议，请在系统上确认本月账单。<br><br>"
                + "为了不影响员工的社保公积金缴纳，请于****年**月**日前将相关费用支付至我司账户：<br><br>"
                + "名 称：仁励窝网络科技（上海）有限公司<br>"
                + "开 户 银 行：中信银行股份有限公司上海外滩支行<br>"
                + "银 行 账 号：8110201012700549506<br><br>"
                + "感谢您的配合，祝工作愉快！<br><br>"
                + "备注：此邮件为系统邮件，请勿直接回复，如有疑问，<span style='color:blue;'> 请发邮件至billing@wowoohr.com</span>";

        MailBean mailBean = new MailBean();
        mailBean.setTo(ReceiveEmail);
        mailBean.setSubject(titleEmail);
        mailBean.setContent(htmlbody);
        File file = new File("/Users/snowwolf-louis/Pictures/photo/1.jpg");
        FileDataSource dataSource = new FileDataSource(file);
        MailAttach mailAttach = new InputStreamMailAttach(dataSource.getInputStream(), "1.jpg");

        List<MailAttach> mailAttaches = new ArrayList<MailAttach>();
        mailAttaches.add(mailAttach);
        mailBean.setMailAttaches(mailAttaches);


        try {
            sendMessage(mailBean);
            System.out.println("发送成功");
        } catch (Exception e) {
            System.out.print(e);
            System.out.println("发送失败");
        }
    }
}
